/**
 * 讲Arrays类型的查询参数转换为json字符串,并且过滤掉其中不必要的查询条件
 */
var queryParamsToJsonStr = (params) => {
	let ps = []

	params.forEach(t => {
		if (t && t.right && t.right.length === 1 && (t.right[0] == undefined || t.right[0] === '')) {
			return
		}

		if (t && t.right && t.right.length === 2) {
			if ((t.right[0] == undefined || t.right[0] === '') &&
				(t.right[1] == undefined || t.right[1] === '')) {
				return
			}
		}

		ps.push({
			left: t.left,
			op: t.op,
			right: t.right
		})
	})

	return JSON.stringify(ps)
}

/**
 * list转menu或者children类型
 * @param {Array} list 数据集合
 * @param {String} parentName 父级标识名称
 * @param {String} idName 数据行唯一标识名称
 * @param {Boolean} depth 是否调用深度遍历，默认只生成2层
 */
var listToMenu = (list, {
	parentName = 'parentId',
	childName = "children",
	idName = 'id',
	depth = false,
	sortName = 'cfgSort'
} = {}) => {
	let trees = []

	if (list && list.length < 1) return trees

	let childrens = []
	list.forEach(t => {
		if (!t[sortName]) t[sortName] = 0

		if (t.parentId == 0 || t.parentId == t.id) {
			t[childName] = []
			trees.push(t)
		} else {
			childrens.push(t)
		}
	})

	// 排序
	trees.sort((a, b) => b[sortName] - a[sortName]);

	// 找出子节点
	if (childrens && childrens.length < 1) return trees

	childrens.forEach(t => {
		trees.forEach(c => {
			if (c[idName] == t[parentName]) {
				t['parentName'] = c.name
				c[childName].push(t)
			}
		})
	})

	// 子节点排序
	trees.forEach(t => {
		t[childName].sort((a, b) => b[sortName] - a[sortName])
	})

	return trees
}

/**
 * 将apis加入到对应的menus中,目前menu只支持两层
 */
var menuListAndApi = (menus, apis, apiMenuName = 'functionId') => {
	let roots = {}
	let nextNodes = {}

	menus.forEach(menu => {
		roots[menu.id] = menu

		if (menu.children && menu.children.length > 0) {
			menu.children.forEach(c => {
				nextNodes[c.id] = c
			})
		}
	})

	// 将api分别纳入对应的menu
	apis.forEach(api => {
		let apiMenuId = api[apiMenuName]

		// 根
		if (roots[apiMenuId]) {
			let menu = roots[apiMenuId]
			api['parentId'] = menu.id

			if (menu.children instanceof Array) {
				menu.children.push(api)
				return
			} else {
				menu.children = [api]
			}
		}

		// 下级
		if (nextNodes[apiMenuId]) {
			let menu = nextNodes[apiMenuId]
			api['parentId'] = menu.id

			if (menu.children instanceof Array) {
				menu.children.push(api)
				return
			} else {
				menu.children = [api]
			}
		}
	})

	return menus
}

/**
 * 解析参数
 * @param {Object} source 原文本-URL
 * @param {Object} params 参数
 */
var analysisText = (source, params) => {
	if (!params || !source) return

	// 批量操作
	if (params instanceof Array) {
		if (params.length < 1) return

		let pt = '{id}'
		let ids = params[0].id ? params[0].id : params[0]

		for (let index = 1; index < params.length; index++) {
			ids = ids + ',' + (params[index].id ? params[index].id : params[index])
		}

		source = source.replace(new RegExp(pt, "gm"), ids);
	}
	// 单个
	else {
		for (let key in params) {
			let pt = '{' + key + '}'
			source = source.replace(new RegExp(pt, "gm"), params[key]);
		}
	}

	return source
}

/**
 * 获取完整的请求路径
 * @param one 一级，一般代表大类
 * @param two 二级，一般代表具体的操作
 */
var getUrl = (one, two, params) => {
	if (!one || !two) return ""

	let type = apiInfo[one]
	if (!type) return

	let op = type[two]
	if (!op) return

	let url = '/' + op['modular'] + op['url']
	return params ? analysisText(url, params) : url
}


/**
 * 根据method返回不同的请求实例
 */
var getHttpByMethod = (axios, method) => {
	if ('get' == method) return axios.get
	if ('post' == method) return axios.post
	if ('delete' == method) {
		return axios['delete']
	}
	if ('put' == method) return axios.put
}

/**
 * 根据不同的method返回不同的请求实例
 * @param one 一级，一般代表大类
 * @param two 二级，一般代表具体的操作
 */
var getHttp = (that, one, two) => {
	if (!one || !two) return ""

	let type = apiInfo[one]
	if (!type) return

	let op = type[two]
	if (!op) return

	return getHttpByMethod(that, op.method)
}

/**
 * 格式化数据,将b的内容赋值到a.只保留a中存在的属性
 */
var fmtAToB = (a, b) => {
	for (let key in a) {
		a[key] = b[key]
	}

	return a
}

/**
 * 获取当前时间
 */
var getNowDate = (da) => {
	if (!da) da = new Date();

	var Y = da.getFullYear(); //年
	var M = da.getMonth() + 1; //月
	var D = da.getDate(); //日
	var h = da.getHours(); //小时
	var m = da.getMinutes(); //分
	var s = da.getSeconds(); //秒

	return Y + "-" +
		(M < 10 ? '0' + M : M) + "-" +
		(D < 10 ? '0' + D : D) + " " +
		(h < 10 ? '0' + h : h) + ":" +
		(m < 10 ? '0' + m : m) + ":" +
		(s < 10 ? '0' + s : s);
}

/**
 * 时间戳转时间
 */
var timestampToTime = (timestamp) => {
	if (!timestamp) return timestamp

	timestamp = timestamp.toString()
	if (timestamp.length != 13 && timestamp.length != 10) return timestamp
	if (timestamp.length == 10) timestamp = parseInt(timestamp) * 1000
	timestamp = parseInt(timestamp)

	var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
	var Y = date.getFullYear() + '-';
	var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
	var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
	var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
	var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
	var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
	return Y + M + D + h + m + s;
}

/**
 * 存储登录信息
 */
var setLoginInfo = (data) => {
	localStorage.setItem('LOGIN_INFO', JSON.stringify(data));
}

// 获取登录信息
var getLoginInfo = () => {
	return JSON.parse(localStorage.getItem('LOGIN_INFO'));
}

// 清除登录信息
var clearLoginInfo = () => {
	localStorage.removeItem('LOGIN_INFO')
}

// 创建用户信息
var createUser = () => {
	return {
		// 临时授权信息
		token: '',
		// 个人资料，一般登陆时初始化
		info: {
			id: 0,
			nickname: '微信测试',
			img: 'sa-resources/admin-logo.png',
		},
		menu: [],
	}
}

/**
 * 判断当前账户是否属于某个角色组
 */
var accountIsRole = (cfgKey) => {
	if (!user.roles) return false
	if (!cfgKey) return false

	let roles = baseConfig.role[cfgKey]
	let myRoles = user.roles

	for (let item in myRoles) {
		for (let index in roles) {
			if (myRoles[item].id == roles[index]) return true
		}
	}


	return false
}

/**
 * 组装表单设计器的url
 */
var getFormUrl = ({
	path = 'index.html',
	params = '',
	position = '/'
} = {}) => {
	let url = URL_FORM + path + '?' + params
	url += '&key=' + user.token
	url += '&baseUrl=' + URL_SERVER_ROOT
	url += '&origin=' + window.origin
	url += '#' + position

	return url
}

/**
 * 如果text长度超出len，则追加省略号
 */
var getTextPre = (text, len = 7) => {
	return text && text.length > len ? text.substring(0, len) + '...' : text
}

/**
 * 格式化表单字段，取出可以被检索的数据项
 */
var queryConfig2List = (fields) => {
	let query = []

	fields.forEach(field => {
		let config = field.__config__
		if (config.searchShow && config.searchShow != 'false') query.push({
			left: field.__vModel__,
			op: config.searchShow,
			right: ['', ''],
			tag: config.tag,
			label: config.label,
			field: field
		})
	})

	return query
}

/**
 * 判断变量是否以某个字符串结尾
 * @param {Object} endStr
 */
String.prototype.endWith = function(endStr) {
	var d = this.length - endStr.length;
	return (d >= 0 && this.lastIndexOf(endStr) == d)
}

// ================================= 用户信息初始化  =================================
user = getLoginInfo() ? getLoginInfo() : createUser()
if (!user.info) {
	user.info = {
		id: user.account.id,
		nickname: user.user && user.user.nickname ? user.user.nickname : '未定义',
		img: user.user && user.user.img ? user.user.img : 'sa-resources/admin-logo.png',
	}
}

// ================================= 基础配置初始化  =================================
var getBaseRoles = () => {
	let keys = []
	for (let key in baseConfig.role) {
		baseConfig.role[key] = []
		keys.push(key)
	}
	
	let params = [{
			left: 'type',
			op: 'op',
			right: ['psoa']
		},
		{
			left: 'cfgKey',
			op: 'in',
			right: keys
		},
	]
	params = queryParamsToJsonStr(params)

	let url = getUrl('pub-config', 'list')
	let http = getHttp(axios, 'pub-config', 'list')
	http(url, {
		params: {
			isPage: false,
			params: params
		}
	}).then(res => {
		if (res.list) {
			res.list.forEach(t => {
				baseConfig.role[t.cfgKey].push(t.cfgValue)
			})
		}
	}).catch((err) => {

	});
}
